package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.constants.CommonConstant;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.mapper.TryJobMapper;
import com.xmy.cultivate.respons.QyWeChartPushRs;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 试岗 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2025-05-07
 */
@Service
//@EnableScheduling  // 测试启用定时任务
public class TryJobServiceImpl extends ServiceImpl<TryJobMapper, TryJob> implements ITryJobService {

    @Autowired
    @Lazy
    ITryJobService iTryJobService;

    @Autowired
    @Lazy
    IPermissionSchoolTeacherService iPermissionSchoolTeacherService;

    @Autowired
    @Lazy
    IMqPushService iMqPushService;

    @Autowired
    @Lazy
    IStaffService iStaffService;

    @Autowired
    @Lazy
    IRecruitService iRecruitService;

    @Autowired
    @Lazy
    IRecruitPushLogService iRecruitPushLogService;

    @Autowired
    @Lazy
    IOrganizationService iOrganizationService;

    @Autowired
    TryJobMapper tryJobMapper;

    /**
     * 试岗满2天推送给校长
     */
    @Override
    @Transactional
//    @Scheduled(fixedRate = 60000)  // 每分钟执行一次
    public void tryJobPush() {
        // 获取当前日期减去2天的日期
        LocalDate now = LocalDate.now();
//        LocalDate threeDaysAgo = now.minusDays(2);  由原先试岗满2天改为1天
        LocalDate threeDaysAgo = now.minusDays(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = threeDaysAgo.format(formatter);

        List<TryJob> tryJobPushList = tryJobMapper.getTryJobPushList(formattedDate);
        if (tryJobPushList != null && !tryJobPushList.isEmpty()) {

            //  按校区分组，获取校区
            Map<Long, List<TryJob>> groupedBySchool = tryJobPushList.stream()
                    .collect(Collectors.groupingBy(TryJob::getSchoolId));
            //获取科目
            Map<Long, List<TryJob>> groupedBySubjects = tryJobPushList.stream().collect( Collectors.groupingBy(TryJob::getSubjectsId));

            List<RecruitPushLog> pushLogs = new ArrayList<>();

            // 遍历每个校区
            for (Map.Entry<Long, List<TryJob>> entry : groupedBySchool.entrySet()) {
                Long schoolId = entry.getKey();
                List<TryJob> jobs = entry.getValue();

                // 获取校长信息
                //原先分配给现在调整为分配主管
                QueryWrapper<PermissionSchoolTeacher> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("school_id", schoolId);
                queryWrapper.eq("type", 1);
                queryWrapper.eq("deleted", 0);
                queryWrapper.eq("subjects_id",  groupedBySubjects.get(entry.getKey()));
                queryWrapper.eq("position_type", 3);
//                queryWrapper.eq("position_type", 1);
                queryWrapper.last("limit 1");
                PermissionSchoolTeacher permissionSchoolTeacher = iPermissionSchoolTeacherService.getOne(queryWrapper);

                if (permissionSchoolTeacher == null) {
                    continue;
                }
                Staff staff = iStaffService.getById(permissionSchoolTeacher.getTeacherId());
                if (staff == null || StringUtils.isBlank(staff.getQyWecharId())) {
                    continue;
                }
                List<String> recruitNames = new ArrayList<>();
                for (TryJob job : jobs) {
                    Recruit recruit = iRecruitService.getById(job.getRecruitId());
                    if (recruit != null) {
                        recruitNames.add(recruit.getName());

                        RecruitPushLog log = new RecruitPushLog();
                        log.setRecruitId(job.getRecruitId());
                        log.setType(1); // 试岗满2天推送类型
                        log.setPushStaffId(staff.getId()); // 设置推送的ID
                        log.setStatus(1);
                        pushLogs.add(log);
                    }
                }
                Organization organization = iOrganizationService.getById(schoolId);

                // 发送企业微信消息
                if (!recruitNames.isEmpty()) {
//                    String content = "您"+organization.getName()+"有试岗人员已满两天：" + String.join("，", recruitNames);
                    String content = "您"+organization.getName()+"有试岗人员已满一天：" + String.join("，", recruitNames);
                    QyWeChartPushRs qyWeChartPushRs = new QyWeChartPushRs();
                    qyWeChartPushRs.setToUser(staff.getQyWecharId());
//                    qyWeChartPushRs.setTitle("试岗满2天");
                    qyWeChartPushRs.setTitle("试岗满1天");
                    qyWeChartPushRs.setContent(content);
                    qyWeChartPushRs.setRemark("请及时点评，确认试岗结果");
                    qyWeChartPushRs.setDateTime(LocalDate.now().toString());
                    qyWeChartPushRs.setLinkUrl(CommonConstant.teacherWebUrl);

                    iMqPushService.pushContentForQyWeChar(qyWeChartPushRs);
                }
            }
            // 批量保存日志
            if (!pushLogs.isEmpty()) {
                iRecruitPushLogService.saveBatch(pushLogs);
            }
        }
    }
}



